package center

import (
	"base"
	"game_server/chanrpc"
	"game_server/logic/center/api"
	"game_server/logic/center/event"
	. "game_server/logic/internal"
	"github.com/golang/protobuf/proto"
	"leaf/gate"
	"proto/base"
	"proto/server/center"
)

type centerSystem struct {
	agent       gate.Agent
	gameAgentId base.AgentId
}

var system = new(centerSystem)

func init() {
	center_api.GameAgentId = system.GameAgentId
	center_api.WriteMsg = system.WriteMsg
}

func init() {
	Skeleton.AfterInit(func() {
		Skeleton.RegisterChanRPC(chanrpc.NewCenterAgent, system.newAgent)
		Skeleton.RegisterChanRPC(chanrpc.CloseCenterAgent, system.closeAgent)
	})
}

func (*centerSystem) GameAgentId() base.AgentId {
	return system.gameAgentId
}

func (*centerSystem) WriteMsg(msg proto.Message) {
	if system.agent == nil {
		base.Logger.Error("not center server agent")
		return
	}

	system.agent.WriteMsg(msg)
}

func (*centerSystem) newAgent(args []interface{}) {
	agent := args[0].(gate.Agent)
	base.Logger.Debug("new center agent, remote address: %s, local address: %s", agent.RemoteAddr(), agent.LocalAddr())
	if system.agent != nil {
		base.Logger.Fatal("repeated center server agent")
	}

	msg := new(proto_server_center.Register)
	msg.Server = proto_base.Server_GameServer
	agent.WriteMsg(msg)

	system.agent = agent

	Event.Notify(center_event.OnConnect)
}

func (*centerSystem) closeAgent(args []interface{}) {
	agent := args[0].(gate.Agent)
	base.Logger.Debug("close center agent, remote address: %s, local address: %s", agent.RemoteAddr(), agent.LocalAddr())

	system.agent = nil

	Event.Notify(center_event.OnDisconnect)
}
